﻿using SocketHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketServer
{
    class Program
    {
        private static Socket serverSocket;
        private static string save_path;
        public static void Init()
        {
            //服务器IP地址
            IPAddress ip = IPAddress.Parse(System.Configuration.ConfigurationManager.AppSettings["ListenIP"]);
            int myProt = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ListenFilePort"]);
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址：端口
            serverSocket.Listen(10);    //设定最多10个排队连接请求            
            Common.ConsoleM(string.Format("启动监听{0}成功", serverSocket.LocalEndPoint.ToString()));
            //通过Clientsoket发送数据
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
        }
        public static void Exit()
        {
            serverSocket.Close();
            serverSocket = null;
        }
        private static void ListenClientConnect()
        {
            while (true)
            {
                if (serverSocket != null)
                {
                    try
                    {
                        Socket clientSocket = serverSocket.Accept();
                        Thread receiveThread = new Thread(Create);
                        receiveThread.Start(clientSocket);
                    }
                    catch
                    {
                        break;
                    }
                }
            }
        }
        public static void Create(object clientSocket)
        {
            Socket client = clientSocket as Socket;
            //获得客户端节点对象
            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
            Common.ConsoleM("访问ip:" + clientep.Address.ToString()+",端口:"+clientep.Port.ToString());
            //if (!clientep.Address.ToString().StartsWith("121."))
            //{
            //    Common.ConsoleM("非法访问ip:" + clientep.Address.ToString() + ",端口:" + clientep.Port.ToString() + ",已拦截。", 2);
            //    return;
            //}
            try
            {
                //获得[消息]   
                string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
                if (SendFileName.StartsWith("F_"))
                {
                    if (string.IsNullOrEmpty(save_path))
                    {
                        save_path = Environment.CurrentDirectory;
                    }
                    else if (File.Exists(save_path))
                    {
                        save_path = Path.GetDirectoryName(save_path);
                    }
                    SendFileName = SendFileName.Substring(2);
                    Common.ConsoleM("文件名:" + SendFileName);
                    //获得[包的大小]   
                    string bagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
                    Common.ConsoleM("包大小:" + bagSize);
                    //获得[包的总数量]   
                    int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
                    Common.ConsoleM("包总量:" + bagCount);
                    //获得[最后一个包的大小]   
                    string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
                    Common.ConsoleM("最后一个包大小:" + bagLast);
                    save_path = Path.Combine(save_path, SendFileName);
                    Common.ConsoleM("保存地址为:" + save_path);
                    //创建一个新文件   
                    FileStream MyFileStream = new FileStream(save_path, FileMode.Create, FileAccess.Write);
                    //已发送包的个数   
                    int SendedCount = 0;
                    while (true)
                    {
                        byte[] data = TransferFiles.ReceiveVarData(client);
                        if (data.Length == 0)
                        {
                            break;
                        }
                        else
                        {
                            SendedCount++;
                            //将接收到的数据包写入到文件流对象   
                            MyFileStream.Write(data, 0, data.Length);
                            //显示已发送包的个数                            
                            Console.WriteLine("                    ");
                            Console.SetCursorPosition(0, Console.CursorTop - 1);
                            string msg = string.Format("{0}-已接收{1}个包,共有{2}个包", DateTime.Now, SendedCount, bagCount);
                            if (SendedCount > bagCount)
                            {
                                msg += ",多接收的包为余量包";
                            }
                            Console.Write(msg);
                        }
                    }
                    //关闭文件流   
                    MyFileStream.Close();
                    //关闭套接字   
                    client.Close();
                    //client.Disconnect(true);  
                    Console.WriteLine("");
                    Common.ConsoleM(SendFileName + "接收完毕！");
                }
                else
                {
                    string command = SendFileName;
                    string[] parts = new string[1];
                    string ret = "command excute ok";
                    if (command == "unzip")
                    {
                        if (File.Exists(save_path))
                        {
                            parts[0] = save_path;
                        }
                        else
                        {
                            command = "压缩包不存在";
                            ret = "unzip excute failed";
                        }
                    }
                    AnalysisCommand.excuteCommand(command, parts);
                    TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(ret));
                }

            }
            catch (Exception ex)
            {
                client.Close();
                Common.ConsoleM(ex.Message);
            }
        }

        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                save_path = args[0];
                if (!Directory.Exists(save_path))
                    Directory.CreateDirectory(save_path);
            }
            Init();
        }
    }
}
